package com.sean.common.mybatis.dialect;
/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.  All third-party contributions are
 * distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */


/**
 * An SQL dialect for DB2.
 * 
 * @author XinWang
 */
public class DB2Dialect extends Dialect {

	public String getLimitString(String sql, int offset, int limit) {
		if (limit == 0)
			limit++;
		if (offset == 0) {
			return sql + " fetch first " + limit + " rows only";
		}
		StringBuilder pagingSelect = new StringBuilder(sql.length() + 200)
				.append("select * from ( select inner2_.*, rownumber() over(order by order of inner2_) as rownumber_ from ( ")
				.append(sql)
				// nest the main query in an outer select
				.append(" ) as inner2_ ) as inner1_ where rownumber_ > ").append(offset)
				.append(" and rownumber_ <=  ").append(offset + limit)
				.append(" order by rownumber_");
		return pagingSelect.toString();
	}

	@Override
	public String getCountString(String originalSql) {
		return "select count(1) from ( " + originalSql + " ) t";
	}

}
